<?php

namespace pos\services\mall;

use pos\extensions\ApiBaseService;
use common\models\mall\MallHoldModel;
use common\models\mall\MallHoldCartModel;
use common\models\mall\MallCartModel;
use pos\services\order\OrderService;


/**
 * Desc 挂单管理
 * @author WMX
 */
class MallHoldService extends ApiBaseService
{


    // 挂单
    public static function hold($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }
            $hold = [
                'type' => $params['type'],
                'phone' => isset($params['phone']) ? $params['phone'] : '',
                'coupon_code' => isset($params['coupon_code']) ? $params['coupon_code'] : '',
                'device' => $device,
                'create_time' => date('Y-m-d H:i:s')
            ];
            $model_id = MallHoldModel::create($hold);



            $hold_cart = [];
            foreach ($params['cart'] as $val) {
                $hold_cart[] = [
                    'user_id' => $val['user_id'],
                    'gid' => $val['gid'],
                    'count' => $val['count'],
                    'state' => $val['state'],
                    'spec' => $val['spec'],
                    'price' => $val['price'],
                    'device' => $val['device'],
                    'hold_id' => $model_id
                ];
            }

            \Yii::$app->db->createCommand()->batchInsert(MallHoldCartModel::tableName(), array_keys($hold_cart[0]), $hold_cart)->execute();

            // 清空购物车
            MallCartModel::deleteAll(['device' => $device]);
            $transaction->commit();
            return self::jsonSuccess([]);
        } catch (\Exception $exc) {
            $transaction->rollBack();
            return self::jsonError($exc->getMessage());
        }
    }



    // 挂单列表
    public static function holdList($params)
    {
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }
            //检索条件
            $query = MallHoldCartModel::find()->alias('mhc')->leftJoin('goods g', 'mhc.gid=g.id');
            $query->where([
                'mhc.device' => $device
            ]);
            $query->select(['mhc.*', 'g.thumb', 'g.name'])->orderBy('mhc.id desc');
            $list = $query->asArray()->all();


            $order = MallHoldModel::getDataAll(['device' => $device], 1, 10000);
            foreach ($order['list'] as &$val) {
                $val['goods'] = [];
                foreach ($list as $cart) {
                    if ($cart['hold_id'] == $val['id']) {
                        $val['goods'][] = $cart;
                    }
                }
            }

            return self::jsonSuccess($order);
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }


    // 取回单据
    // 执行批量加购，清空现有购物车
    public static function holdBack($params)
    {

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }

            $hold = MallHoldModel::getDataOne(['id' => $params['id']]);
            if (empty($hold)) {
                throw new \Exception('数据异常');
            }

            // 清空购物车
            MallCartModel::deleteAll(['device' => $device]);

            $cart = MallHoldCartModel::getAll(['hold_id' => $params['id']]);

            foreach ($cart as &$val) {
                unset($val['id']);
                unset($val['hold_id']);
            }

            \Yii::$app->db->createCommand()->batchInsert(MallCartModel::tableName(), array_keys($cart[0]), $cart)->execute();

            MallHoldModel::deleteAll(['id' => $params['id']]);
            MallHoldCartModel::deleteAll(['hold_id' => $params['id']]);
            $transaction->commit();
            return self::jsonSuccess([]);
        } catch (\Exception $exc) {
            $transaction->rollBack();
            return self::jsonError($exc->getMessage());
        }
    }

    // 挂单支付
    public static function holdPay($params) {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }

            $hold = MallHoldModel::getDataOne(['id' => $params['id']]);
            
            $back_res = self::holdBack($params);
            if($back_res['code'] != 0) {
                throw new \Exception('支付异常');
            }

            $res = OrderService::submit([
                'type' => $hold['type'],
                'phone' => $hold['phone'],
                'coupon_code' => $hold['coupon_code'],
            ]);

            $transaction->commit();
            return $res;
        } catch (\Exception $exc) {
            $transaction->rollBack();
            return self::jsonError($exc->getMessage());
        }
    }
}
